package com.century.sjt.activity.Topic;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.adapter.CommonAdapter;
import com.century.sjt.adapter.mCommentListAdapter;
import com.century.sjt.adapter.mPraiseListAdapter;
import com.century.sjt.adapter.TopicCommentListAdapter;
import com.century.sjt.adapter.ViewHolder;
import com.century.sjt.entity.Comment;
import com.century.sjt.entity.Praise;
import com.century.sjt.entity.SjtUser;
import com.century.sjt.fragment.SocialTabSquareFragment;
import com.century.sjt.util.Constant;
import com.century.sjt.util.ScrollViewListener;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.ListViewForScrollView;
import com.century.sjt.widget.ObservableScrollView;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.century.sjt.widget.picture.IBaseConstant;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;


public class MyTopicDetail extends BaseActivity {

    private ImageButton btnSys;                                     //返回按钮
    private TextView mTitle;                                        //程序标题
    private LinearLayout leftLinLayout;                             //左边的线性布局
    private TextView mTextView;

    private RoundedImageView mNetworkImageView;
    private TextView mNickName;
    private TextView mCreateDateTime;
    private TextView mContent;
    private ImageView mNetworkImageView1;
    private ImageView mNetworkImageView2;
    private ImageView mNetworkImageView3;
    private ImageView mNetworkImageView4;
    private ImageView mNetworkImageView5;
    private ImageView mNetworkImageView6;
    private ImageView mNetworkImageView7;
    private ImageView mNetworkImageView8;
    private ImageView mNetworkImageView9;
    private LinearLayout mLinearLayoutRow1;
    private LinearLayout mLinearLayoutRow2;
    private LinearLayout mLinearLayoutRow3;
    private TextView mCommentNum;
//    private TextView mCommentNum2;
    private TextView mPraiseNum;


    private ListViewForScrollView mListViewForScrollView;

    private LinearLayout mllComment;
    private LinearLayout mllbgllComment;

    private String topicId;
    private String option = "";

    private EditText mEditText;
    private Handler mHandler;

    private String shareContent;
    private String sharethemePic1;
    //    private Button loadMore;                     //更多评论按钮
    boolean isLastRow = false;
    private int SEND_LOAD_MORE_NUM = 1;            //评论翻页的页数

    private String shareUrl;                   //分享图片

    //    private int first=1;
    private SjtTitleBar titleBar;
    //  内容
    private String mainContent, mainImage;
    private ObservableScrollView osvContent;
    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private Boolean isDataChangeOk = true;

//    private LinearLayout layout_Like;
//    private TextView tvLike;
//    private String likeList;
    private List<String> praiseList = new ArrayList<>();
    private String TextPraiseNick;

    public TextView icon_linear_like;
    public TextView icon_information;
    public TextView icon_trash;
    public TextView icon_share;

    private List<Comment> mCommentList = new ArrayList<>();
    private List<Praise> mPraiseList = new ArrayList<>();
    private String mPraiseNameList = "";
    private SjtUser mUser;


    //首页tab
    private LinearLayout mlltab1, mlltab2;
    private FrameLayout mlltab1_btn, mlltab2_btn;
    private View vwTip1, vwTip2;

    private ListViewForScrollView listView1;
    private ListViewForScrollView listView2;
    private mCommentListAdapter adapter1;
    private mPraiseListAdapter adapter2;
    private List<ImageView> LisetImageView=new ArrayList<>();

    private String typeTab = "1";//typeTab上拉更多时判断，1：评论 2：点赞
    private int currentPage1 = 1;
    private int currentPage2 = 1;
    private boolean isDataChange1Ok=true;
    private boolean isDataChange2Ok=true;
    private LinearLayout layoutDelete;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_topic_detail);
        initView();
        initEvent();
        initData();



    }

    @Override
    protected void initView() {
        //       标题栏
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        titleBar.setTitle(getResources().getString(R.string.tab_friends_zone));
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.activity_list_refesh);

        mllComment = (LinearLayout) findViewById(R.id.ll_my_topic_detail_topicComment);
        mllbgllComment = (LinearLayout) findViewById(R.id.bg_my_topic_detail_black_alpha);

        Intent intent = this.getIntent();
        topicId = intent.getStringExtra("topicId");
        option = intent.getStringExtra("option");

        listView1 = (ListViewForScrollView) findViewById(R.id.lv_my_topic_detail_topicCommentList);
        listView2 = (ListViewForScrollView) findViewById(R.id.lv_my_topic_detail_topicpraiseList);
        mlltab1_btn = (FrameLayout) findViewById(R.id.lltab_1_top);
        mlltab2_btn = (FrameLayout) findViewById(R.id.lltab_2_top);
        mlltab1 = (LinearLayout) findViewById(R.id.comment_list);
        mlltab2 = (LinearLayout) findViewById(R.id.praise_list);
        vwTip1 = findViewById(R.id.vw_red_tip1);
        vwTip2 = findViewById(R.id.vw_red_tip2);
        vwTip2.setBackgroundColor(0x00000000);
        mTextView = (TextView) findViewById(R.id.tv_my_topic_detail);
        mTextView.setText(topicId);

        mNetworkImageView = (RoundedImageView) findViewById(R.id.niv_social_zone_image);
        mNickName = (TextView) findViewById(R.id.niv_social_zone_title);
        mCreateDateTime = (TextView) findViewById(R.id.niv_social_zone_time);
        mContent = (TextView) findViewById(R.id.niv_social_zone_content);
        mNetworkImageView1 = (ImageView) findViewById(R.id.niv_social_zone_image1);
        mNetworkImageView2 = (ImageView) findViewById(R.id.niv_social_zone_image2);
        mNetworkImageView3 = (ImageView) findViewById(R.id.niv_social_zone_image3);
        mNetworkImageView4 = (ImageView) findViewById(R.id.niv_social_zone_image4);
        mNetworkImageView5 = (ImageView) findViewById(R.id.niv_social_zone_image5);
        mNetworkImageView6 = (ImageView) findViewById(R.id.niv_social_zone_image6);
        mNetworkImageView7 = (ImageView) findViewById(R.id.niv_social_zone_image7);
        mNetworkImageView8 = (ImageView) findViewById(R.id.niv_social_zone_image8);
        mNetworkImageView9 = (ImageView) findViewById(R.id.niv_social_zone_image9);
        mLinearLayoutRow1 = (LinearLayout) findViewById(R.id.ll_social_zone_row1);
        mLinearLayoutRow2 = (LinearLayout) findViewById(R.id.ll_social_zone_row2);
        mLinearLayoutRow3 = (LinearLayout) findViewById(R.id.ll_social_zone_row3);
        mCommentNum = (TextView) findViewById(R.id.tv_my_social_zone_commentNum);

        mPraiseNum = (TextView) findViewById(R.id.tv_my_social_zone_praiseNum);
        mEditText = (EditText) findViewById(R.id.et_my_topic_detail_send);
        osvContent = (ObservableScrollView) findViewById(R.id.osv_content);
        icon_linear_like = (TextView) findViewById(R.id.icon_linear_like);
        icon_information = (TextView) findViewById(R.id.icon_information);
        icon_trash = (TextView) findViewById(R.id.icon_trash);
        icon_share = (TextView) findViewById(R.id.icon_share);
        layoutDelete = (LinearLayout) findViewById(R.id.ll_delete);
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        icon_linear_like.setTypeface(iconfont);
        icon_information.setTypeface(iconfont);
        icon_trash.setTypeface(iconfont);
        icon_share.setTypeface(iconfont);
        mNetworkImageView1.setVisibility(View.GONE);
        mNetworkImageView2.setVisibility(View.GONE);
        mNetworkImageView3.setVisibility(View.GONE);
        mNetworkImageView4.setVisibility(View.GONE);
        mNetworkImageView5.setVisibility(View.GONE);
        mNetworkImageView6.setVisibility(View.GONE);
        mNetworkImageView7.setVisibility(View.GONE);
        mNetworkImageView8.setVisibility(View.GONE);
        mNetworkImageView9.setVisibility(View.GONE);

        LisetImageView.add(mNetworkImageView1);
        LisetImageView.add(mNetworkImageView2);
        LisetImageView.add(mNetworkImageView3);
        LisetImageView.add(mNetworkImageView4);
        LisetImageView.add(mNetworkImageView5);
        LisetImageView.add(mNetworkImageView6);
        LisetImageView.add(mNetworkImageView7);
        LisetImageView.add(mNetworkImageView8);
        LisetImageView.add(mNetworkImageView9);


    }

    @Override
    protected void initEvent() {
        //        删除话题

        layoutDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MyTopicDetail.this);
                builder.setTitle(getResources().getString(R.string.text_prompt));
                builder.setMessage(getString(R.string.error_is_delete));
                builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deleteTopic(topicId);
                    }
                });
                builder.setNegativeButton(getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(false);
                builder.create().show();
            }
        });
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter1.notifyDataSetChanged();
                        adapter2.notifyDataSetChanged();
                        TipUtil.closeProgressDialog();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isDataChangeOk = true;
                        isDataChange1Ok = true;
                        isDataChange2Ok = true;
                        currentPage1 = 1;
                        currentPage2 = 1;
                        rePraise();
                        break;
                    case 3:
                        if (typeTab.equals("1")) {
                            if (isDataChange1Ok){
                                currentPage1++;
                                reTopicCommentList("1");
                            }

                        } else if (typeTab.equals("2")) {
                            if (isDataChange2Ok){
                                currentPage2++;
                                reTopicCommentList("2");
                            }

                        }
                        break;

                }
            }
        };
        listView1.setVisibility(View.VISIBLE);
        listView2.setVisibility(View.GONE);
        mlltab1_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeTab = "1";
                mlltab1.setVisibility(View.VISIBLE);
                mlltab2.setVisibility(View.GONE);
                listView1.setVisibility(View.VISIBLE);
                listView2.setVisibility(View.GONE);
                vwTip1.setBackgroundColor(getResources().getColor(R.color.textdefault_main));
                vwTip1.startAnimation(AnimationUtils.loadAnimation(MyTopicDetail.this, R.anim.scale));
                vwTip2.setBackgroundColor(0x00000000);
            }
        });

        mlltab2_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeTab = "2";
                mlltab1.setVisibility(View.GONE);
                mlltab2.setVisibility(View.VISIBLE);
                listView1.setVisibility(View.GONE);
                listView2.setVisibility(View.VISIBLE);
                vwTip2.setBackgroundColor(getResources().getColor(R.color.textdefault_main));
                vwTip2.startAnimation(AnimationUtils.loadAnimation(MyTopicDetail.this, R.anim.scale));
                vwTip1.setBackgroundColor(0x00000000);
            }
        });

        mEditText.setFocusable(true);
        mEditText.setFocusableInTouchMode(true);

        ScrollViewListener scrollViewListener = new ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                int scrollY = scrollView.getScrollY();
                float i = (float) scrollY;
//                滑动到底部刷新
                int height = scrollView.getHeight();
                int scrollViewMeasuredHeight = scrollView.getChildAt(0).getMeasuredHeight();
                if ((scrollY + height) == scrollViewMeasuredHeight) {
                    //加载更多功能的代码
                        Message msg = new Message();
                        msg.what = 3;
                        mHandler.sendMessage(msg);
                }
            }
        };
        osvContent.setScrollViewListener(scrollViewListener);
        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });

        adapter1 = new mCommentListAdapter(MyTopicDetail.this,mQueue,mCommentList);
        listView1.setAdapter(adapter1);
        adapter2 = new mPraiseListAdapter(MyTopicDetail.this,mQueue,mPraiseList);
        listView2.setAdapter(adapter2);
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);

        //评论列表
        mListViewForScrollView = (ListViewForScrollView) findViewById(R.id.lv_my_topic_detail_topicCommentList);

        mListViewForScrollView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isLastRow && scrollState == this.SCROLL_STATE_IDLE) {
                    isLastRow = false;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0) {
                    isLastRow = true;
                }
            }
        });


        if (option.equals("comment")) {
            mllComment.setVisibility(View.VISIBLE);
            mllbgllComment.setVisibility(View.VISIBLE);
            mEditText.requestFocus();
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                               public void run() {
                                   InputMethodManager inputManager =
                                           (InputMethodManager) mEditText.getContext().getSystemService(MyTopicDetail.INPUT_METHOD_SERVICE);
                                   inputManager.showSoftInput(mEditText, 0);
                               }

                           },
                    680);

        }

        //九宫格显示图片（开始）
        mNetworkImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyTopicDetail.this, HomepageActivity.class).putExtra("userId", mUser.getSysid());
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });



    }

    @Override
    protected void initData() {
        rePraise();
//        reTopicCommentList();  //话题的评论列表获取

    }
    @Override
    public void onResume() {
        super.onResume();
        listView1.setFocusable(false);
        listView2.setFocusable(false);
    }

    private void PraiseNumandcommentNum(int praiseNum, int commentNum) {
        if (praiseNum == 0) {
            mPraiseNum.setText(getResources().getString(R.string.text_good));
        } else {
            String pNum = Integer.toString(praiseNum);
            mPraiseNum.setText(pNum);
        }

        if (commentNum == 0) {
            mCommentNum.setText(getResources().getString(R.string.text_comment));
        } else {
            String cNum2 = Integer.toString(commentNum);
            mCommentNum.setText(cNum2);
        }
    }


    //隐藏输入法
    public void hideSoftInputView() {
        InputMethodManager manager = ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE));
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void deleteTopic(final String topicId) {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), MyTopicDetail.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.DeleteTopicHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("删除话题接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        TipUtil.closeProgressDialog();

                        Message msg1 = new Message();
                        msg1.what = 2;
                        SocialTabSquareFragment.mHandler.sendMessage(msg1);
                        finish();
                    } else {//失败
                        TipUtil.showToast(message, MyTopicDetail.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), MyTopicDetail.this, 1);
                }
                TipUtil.closeProgressDialog();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MyTopicDetail.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("sysId", topicId);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    private void reTopicCommentList(final String type) {
//        type 1：评论 2：点赞
        isDataChangeOk = false;
        isDataChange1Ok = false;
        isDataChange2Ok = false;
        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, Constant.TopicCommentListHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                isDataChangeOk = true;
                Log.e("话题评论列表", s);
                try {
                    JSONTokener jsonTokener = new JSONTokener(s);
                    JSONObject res = (JSONObject) jsonTokener.nextValue();
                    String code = res.getString("code");
                    String Message = res.getString("message");
                    if (code.equals("200")) {
                        JSONObject data = res.getJSONObject("data");
//                        if (data.length() != Constant.PAGESIZE) {
//                            isDataChangeOk = false;
//                        }
                        isDataChange1Ok = true;
                        isDataChange2Ok = true;
                        if ("1".equals(type)){
                            for (int i = 0; i < data.length(); i++) {
                                //评论
                                int count = 0 ;
                                JSONArray commentList = data.getJSONArray("commentList");
                                if (commentList.length()!=Constant.PAGESIZE)
                                    isDataChange1Ok=false;
                                for (int j = 0;j<commentList.length();j++){
                                    JSONObject comment =(JSONObject) commentList.get(j);
                                    JSONObject auser = (JSONObject) comment.getJSONObject("user");
                                    SjtUser user1 = new SjtUser();
                                    user1.setSysid(auser.getString("sysId"));
                                    user1.setNickName(auser.getString("nickName"));
                                    user1.setImage(auser.getString("image"));
                                    Comment comment1 = new Comment();
                                    comment1.setSysId(comment.getString("sysId"));
                                    comment1.setContent(comment.getString("content"));
                                    comment1.setCreateDateTime(comment.getString("createDateTime"));
                                    comment1.setUser(user1);
                                    mCommentList.add(comment1);
                                    count++;
                                }
                                mCommentNum.setText(count+"");
                            }
                        }else {
                            JSONArray praiseList = data.getJSONArray("praiseList");
                            if (praiseList.length()!=Constant.PAGESIZE)
                                isDataChange2Ok=false;
                            int count = 0;
                            for (int j = 0;j<praiseList.length();j++){
                                JSONObject praise =(JSONObject) praiseList.get(j);
                                JSONObject auser = (JSONObject) praise.getJSONObject("user");
                                SjtUser user1 = new SjtUser();
                                user1.setSysid(auser.getString("sysId"));
                                user1.setNickName(auser.getString("nickName"));
                                user1.setImage(auser.getString("image"));
                                if (j>0){
                                    String mName = "、"+user1.getNickName();
                                    mPraiseNameList+=mName;
                                }else {
                                    mPraiseNameList+=user1.getNickName()+" ";
                                }

                                Praise praise1 = new Praise();
                                praise1.setSysId(praise.getString("sysId"));
                                praise1.setContent(praise.getString("content"));
                                praise1.setCreateDateTime(praise.getString("createDateTime"));
                                praise1.setUser(user1);
                                mPraiseList.add(praise1);
                                count++;
                            }
                            mPraiseNum.setText(count+"");
                        }


                        //Toast.makeText(MyTopicDetail.this, "200！", Toast.LENGTH_LONG).show();
                    } else {
                        isDataChangeOk = false;
//                        loadMore.setText("没有更多评论");
//                        loadMore.setEnabled(false);
//                        Toast.makeText(MyTopicDetail.this,Message,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isDataChangeOk = true;
                if ("1".equals(type)){
                    isDataChange1Ok=true;
                    currentPage1--;
                }else {
                    isDataChange2Ok = true;
                    currentPage2--;
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                String num = String.valueOf(SEND_LOAD_MORE_NUM);
                Map<String, String> map = new HashMap<>();
                map.put("topicId", topicId);
                if ("1".equals(type)){
                    map.put("paging.currentPage", currentPage1 + "");
                }else {
                    map.put("paging.currentPage", currentPage2 + "");
                }

                map.put("paging.pageSize", Constant.PAGESIZE + "");
                map.put("extType",type);
                return map;
            }
        };
        mQueue.add(stringRequest1);


        //话题的评论列表（结束）
    }


    public void showComment(View view) {


        mllComment.setVisibility(View.VISIBLE);
        mllbgllComment.setVisibility(View.VISIBLE);

        mEditText.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) mEditText.getContext().getSystemService(MyTopicDetail.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(mEditText, 0);
                           }

                       },
                680);

    }

    public void showCommentCancel(View view) {
        hideSoftInputView();
        mllComment.setVisibility(View.GONE);
        mllbgllComment.setVisibility(View.GONE);
    }

    public void sendMyTopicDetail(View view) {
        final String content = mEditText.getText().toString();
        if (content.trim().equals("")) {
            Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_input_isnull), Toast.LENGTH_LONG).show();
        } else {

            StringRequest stringRequest2 = new StringRequest(Request.Method.POST, Constant.TopicCommentHost, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    try {
                        JSONTokener jsonTokener = new JSONTokener(s);
                        JSONObject res = (JSONObject) jsonTokener.nextValue();
                        String code = res.getString("code");
                        String Message = res.getString("message");
                        if (code.equals("200")) {
                            Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_comment_success), Toast.LENGTH_LONG).show();
                            currentPage1 = 1;
                            //更新第二个评论数
                            Timer timer = new Timer();
                            TimerTask tast = new TimerTask() {
                                @Override
                                public void run() {
//                                    rePraise();
                                    mCommentList.clear();
                                    reTopicCommentList("1");
                                }
                            };
                            timer.schedule(tast, 1000);


                        } else {
                            Toast.makeText(MyTopicDetail.this, Message, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    String userId = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("userId", "");


                    Map<String, String> map = new HashMap<>();
                    map.put("loginId", userId);
                    map.put("topicSysId", topicId);
                    map.put("content", content);
                    return map;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    String cookie = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("cookie", "");
                    String rememberMeValue = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("rememberMe", "");
                    HashMap localHashMap = new HashMap();
                    String cookieValue = cookie + ";" + rememberMeValue;
                    Log.e("cookie", cookieValue);
                    localHashMap.put("Cookie", cookieValue);
                    return localHashMap;
                }
            };
            mQueue.add(stringRequest2);
            hideSoftInputView();
            mllComment.setVisibility(View.GONE);
            mllbgllComment.setVisibility(View.GONE);


        }

        mEditText.setText("");
    }

    public void sendPraise(View view) {
        StringRequest stringRequest3 = new StringRequest(Request.Method.POST, Constant.TopicPraiseHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONTokener jsonTokener = new JSONTokener(s);
                    JSONObject res = (JSONObject) jsonTokener.nextValue();
                    String code = res.getString("code");
                    String Message = res.getString("message");
                    if (code.equals("200")) {
                        JSONObject data = res.getJSONObject("data");
                        String praiseNum = data.getString("praiseNum");
                        String praiseSwitch = data.getString("praiseSwitch");
                        if (praiseNum.equals("0")) {
                            mPraiseNum.setText(getResources().getString(R.string.text_good));
                        } else {
                            mPraiseNum.setText(praiseNum);
                        }
                        mPraiseList.clear();
                        String mPraiseNameList = "";
                        JSONArray praiseList = data.getJSONArray("praiseList");
                        if (praiseList.length()!=Constant.PAGESIZE)
                            isDataChange2Ok=false;
                        for (int j = 0;j<praiseList.length();j++){
                            JSONObject praise =(JSONObject) praiseList.get(j);
                            JSONObject auser = (JSONObject) praise.getJSONObject("user");
                            SjtUser user1 = new SjtUser();
                            user1.setSysid(auser.getString("sysId"));
                            user1.setNickName(auser.getString("nickName"));
                            user1.setImage(auser.getString("image"));
                            if (j>0){
                                String mName = "、"+user1.getNickName();
                                mPraiseNameList+=mName;
                            }else {
                                mPraiseNameList+=user1.getNickName()+" ";
                            }

                            Praise praise1 = new Praise();
                            praise1.setSysId(praise.getString("sysId"));
                            praise1.setContent(praise.getString("content"));
                            praise1.setCreateDateTime(praise.getString("createDateTime"));
                            praise1.setUser(user1);
                            mPraiseList.add(praise1);
                        }
//
                        //点赞成功、取消提示
                        if (praiseSwitch.equals("1")) {
                            Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_isgood_yes), Toast.LENGTH_LONG).show();
                        } else if (praiseSwitch.equals("0")) {
                            Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_isgood_no), Toast.LENGTH_LONG).show();
                        }
                        adapter2.notifyDataSetChanged();
                        //更新
//                        Timer timer = new Timer();
//                        TimerTask tast = new TimerTask() {
//                            @Override
//                            public void run() {
//                                rePraise();
//                            }
//                        };
//                        timer.schedule(tast, 200);
                    } else {
                        Toast.makeText(MyTopicDetail.this, Message, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                String userId = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("userId", "");
                Map<String, String> map = new HashMap<>();
                map.put("loginId", userId);
                map.put("topicSysId", topicId);
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String cookie = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("cookie", "");
                String rememberMeValue = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest3);

    }

    private void rePraise() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting),MyTopicDetail.this);

        //显示详细内容（开始）
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.TopicDetailHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                TipUtil.closeProgressDialog();
                try {
                    JSONTokener jsonTokener = new JSONTokener(s);
                    JSONObject res = (JSONObject) jsonTokener.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    //Log.e("话题详情",s);
                    JSONObject data = res.getJSONObject("data");
                    if (code.equals("200")) {
                        if (data.length() != Constant.PAGESIZE) {
                            isDataChangeOk = false;
                        }
                        //用户
                        //话题
                        topicId = data.getString("sysId");
                        String content = data.getString("content");
                        mainContent = data.getString("content");

                        String themePic = data.getString("themePic");
                        shareUrl = data.getString("shareUrl");
                        JSONObject user = data.getJSONObject("user");
                        mUser = new SjtUser();
                        mUser.setSysid(user.getString("sysId"));
                        mUser.setNickName(user.getString("nickName"));
                        mUser.setImage(user.getString("image"));
//                            Log.e("image1", image);
//                            Log.e("获取话题", createDateTime);
                        JSONArray praiseList = data.getJSONArray("praiseList");
                        mPraiseList.clear();
                        if (praiseList.length()!=Constant.PAGESIZE)
                            isDataChange2Ok=false;
                        for (int j = 0;j<praiseList.length();j++){
                            JSONObject praise =(JSONObject) praiseList.get(j);
                            JSONObject auser = (JSONObject) praise.getJSONObject("user");
                            SjtUser user1 = new SjtUser();
                            user1.setSysid(auser.getString("sysId"));
                            user1.setNickName(auser.getString("nickName"));
                            user1.setImage(auser.getString("image"));
                            if (j>0){
                                String mName = "、"+user1.getNickName();
                                mPraiseNameList+=mName;
                            }else {
                                mPraiseNameList+=user1.getNickName()+" ";
                            }

                            Praise praise1 = new Praise();
                            praise1.setSysId(praise.getString("sysId"));
                            praise1.setContent(praise.getString("content"));
                            praise1.setCreateDateTime(praise.getString("createDateTime"));
                            praise1.setUser(user1);
                            mPraiseList.add(praise1);
                        }
                        JSONArray commentList = data.getJSONArray("commentList");
                        if (commentList.length()!=Constant.PAGESIZE)
                            isDataChange1Ok=false;
                        mCommentList.clear();
                        for (int j = 0;j<commentList.length();j++){
                            JSONObject comment =(JSONObject) commentList.get(j);
                            JSONObject auser = (JSONObject) comment.getJSONObject("user");
                            SjtUser user1 = new SjtUser();
                            user1.setSysid(auser.getString("sysId"));
                            user1.setNickName(auser.getString("nickName"));
                            user1.setImage(auser.getString("image"));
                            Comment comment1 = new Comment();
                            comment1.setSysId(comment.getString("sysId"));
                            comment1.setContent(comment.getString("content"));
                            comment1.setCreateDateTime(comment.getString("createDateTime"));
                            comment1.setUser(user1);
                            mCommentList.add(comment1);
                        }


                        int praiseNum = data.getInt("praiseNum");
                        int commentNum = data.getInt("commentNum");
                        String createDateTime = data.getString("createDateTime");

                        shareContent = content;
                        String imgUrl = Constant.ImageHost_Small + mUser.getImage();
                        Glide.with(MyTopicDetail.this).load(imgUrl).into(mNetworkImageView);


                        PraiseNumandcommentNum(praiseNum, commentNum);


//
                        mNickName.setText(mUser.getNickName());
                        mCreateDateTime.setText(createDateTime);

                        content = content.replaceAll("\\[.{2,3}\\]", "[表情]");
                        mContent.setText(content);
                        String cNum = Integer.toString(commentNum);
                        mShowImage(themePic);
                        mCommentNum.setText(cNum);

                        String userId = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE).getString("userId", "");
                        if (userId.equals(mUser.getSysid())){
                            layoutDelete.setVisibility(View.VISIBLE);
                        }else {
                            layoutDelete.setVisibility(View.GONE);
                        }
                        //Toast.makeText(MyTopicDetail.this, message, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MyTopicDetail.this, message, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    TipUtil.closeProgressDialog();
                    e.printStackTrace();
                    Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MyTopicDetail.this, getResources().getString(R.string.error_network), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("topicSysId", topicId);
                return map;
            }
        };
        mQueue.add(stringRequest);

        //显示详细内容（结束）
    }


    public void showShare(View view) {
//图片不能为空，地址要有图片
//sjt
        ShareSDK.initSDK(MyTopicDetail.this);
        OnekeyShare oks = new OnekeyShare();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitleUrl(shareUrl);
        oks.setTitle(Constant.SHARE_TITLE);
//        String loginid=SjtMainActivity.mainSharePreferences.getString("loginid","");
//        oks.setImagePath(Constant.CAMERA_PICTURE_PATH + loginid);
        oks.setImageUrl(Constant.ImageHost_Big + mainImage);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(shareContent);
//        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        oks.setUrl(shareUrl);
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(getString(R.string.app_name));
        oks.show(MyTopicDetail.this);

//zb
//            ShareSDK.initSDK(MyTopicDetail.this);
//            OnekeyShare oks = new OnekeyShare();
//            //关闭sso授权
//            oks.disableSSOWhenAuthorize();
//
//// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
//            //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
//            // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//            oks.setTitle(mainContent);
//            oks.setTitleUrl("http://www.sjct518.com");
//            // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
////        oks.setTitleUrl("http://sharesdk.cn");
//            // text是分享文本，所有平台都需要这个字段
//            oks.setText(mainContent+" 链接地址："+"http://www.sjct518.com");
//            // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
////        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
//            //微信好友中网络图片
//            oks.setImageUrl(mainImage);
//            // url仅在微信（包括好友和朋友圈）中使用
//            oks.setUrl("http://www.sjct518.com");
//            // comment是我对这条分享的评论，仅在人人网和QQ空间使用
////        oks.setComment("我是测试评论文本");
//            // site是分享此内容的网站名称，仅在QQ空间使用
////        oks.setSite(getString(R.string.app_name));
//            // siteUrl是分享此内容的网站地址，仅在QQ空间使用
////        oks.setSiteUrl("http://192.168.0.188:9080/xmsmt/upload/image/qiaodan_ticket_logo.png");
//
//
//// 启动分享GUI
//            oks.show(MyTopicDetail.this);
//

    }
    private void mShowImage(String themePic){
        final String [] newsplitstr = themePic.split("\\|");
        final String[] imageUrls = new String[newsplitstr.length];

        mLinearLayoutRow1.setVisibility(View.GONE);
        mLinearLayoutRow2.setVisibility(View.GONE);
        mLinearLayoutRow3.setVisibility(View.GONE);
        if (newsplitstr.length!=0){
            mLinearLayoutRow1.setVisibility(View.VISIBLE);}
        if (newsplitstr.length>3){
            mLinearLayoutRow2.setVisibility(View.VISIBLE);}
        if (newsplitstr.length>6){
            mLinearLayoutRow3.setVisibility(View.VISIBLE);}
        for (int i=0;i<newsplitstr.length;i++){
            String aimgUrl = Constant.ImageHost_Small + newsplitstr[i];
            imageUrls[i] = Constant.ImageHost_Big + newsplitstr[i];
            if (i>0)
                mLinearLayoutRow1.setVisibility(View.VISIBLE);
            if (i>3)
                mLinearLayoutRow2.setVisibility(View.VISIBLE);
            if (i>6)
                mLinearLayoutRow3.setVisibility(View.VISIBLE);
            ImageView ShowView=LisetImageView.get(i);
            ShowView.setVisibility(View.VISIBLE);
            Glide.with(MyTopicDetail.this).load(aimgUrl).into(ShowView);
        }
        mNetworkImageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,0);
            }
        });
        mNetworkImageView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,1);
            }
        });
        mNetworkImageView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,2);
            }
        });
        mNetworkImageView4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,3);
            }
        });
        mNetworkImageView5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,4);
            }
        });
        mNetworkImageView6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,5);
            }
        });
        mNetworkImageView7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,6);
            }
        });
        mNetworkImageView8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,7);
            }
        });
        mNetworkImageView9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImage(imageUrls,8);
            }
        });
        //九宫格图片显示（结束）

    }

    private void showImage(String[] imageUrls, int dot) {
//        Intent intent = new Intent(MyTopicDetail.this, ImageShowActivity.class);
//        intent.putExtra("imgid", imgid);
//        startActivity(intent);
        Intent intent = new Intent(MyTopicDetail.this, ZonePictureActivity.class);
        intent.putExtra(IBaseConstant.PICTURE_VIEWER_DEFAULT_POSTION, dot);
        intent.putExtra(IBaseConstant.PICTURE_VIEWER_DATASOURCE, imageUrls);
        startActivity(intent);
    }


}
